import sounddevice as sd
import numpy as np
import queue
import time
from .base import AudioSource

class SystemAudioSource(AudioSource):
    """系统音频源"""
    def __init__(self, chunk_size: int = 1024, channels: int = 1, rate: int = 16000):
        self.chunk_size = chunk_size
        self.channels = channels
        self.rate = rate
        self.audio_queue = queue.Queue()
        self.is_running = False
        self.stream = None
        self.buffer = []

    def audio_callback(self, indata, frames, time, status):
        if status:
            print(f"状态: {status}")
        self.buffer.extend(indata[:, 0])
        if len(self.buffer) >= self.rate:
            audio_data = np.array(self.buffer[:self.rate])
            self.buffer = self.buffer[self.rate:]
            self.audio_queue.put(audio_data)

    def start(self):
        self.is_running = True
        print("开始捕获系统音频...")
        print("支持的设备:")
        devices = sd.query_devices()
        for i, device in enumerate(devices):
            print(f"{i}: {device['name']}")
        default_output = sd.query_devices(kind='output')
        print(f"\n使用默认输出设备: {default_output['name']}")
        try:
            with sd.InputStream(callback=self.audio_callback,
                              channels=self.channels,
                              samplerate=self.rate,
                              dtype=np.float32):
                print("\n正在监听系统音频，按 Ctrl+C 停止...")
                print("=" * 50)
                while self.is_running:
                    time.sleep(0.1)
        except KeyboardInterrupt:
            print("\n停止捕获系统音频...")
        finally:
            self.stop()

    def stop(self):
        self.is_running = False 